import json
from utils import ReUtils, MysqlConnectInstance

#0.初始化任务，将历史文章地址插入数据库中

# 将当天数据写入 Mysql
def write_data_to_mysql(object_list):
    connection = MysqlConnectInstance().get_connection()
    data_to_insert = [(
        ReUtils.extract_date(item['title']),
        item['url']
    ) for item in object_list]
    if connection.is_connected():
        print("成功连接到数据库")

        # 创建游标
        cursor = connection.cursor()

        # SQL 插入语句
        insert_query = """
         INSERT INTO mp_url_log (`rate_date`, `url`)
         VALUES (%s, %s)
         """

        # 批量插入数据
        cursor.executemany(insert_query, data_to_insert)

        # 提交更改
        connection.commit()
        print(f"成功插入 {cursor.rowcount} 条记录")
    pass


# 替换函数
def replace_date(match):
    year = match.group(1)
    month = match.group(2)
    day = match.group(3)
    return f"{year}-{month}-{day}"


def read_json_file(path):
    with open(path, 'r') as f:
        data = json.load(f)
        return data


if __name__ == '__main__':
    exchange_urls = read_json_file('exchange_ngn_urls.json')
    write_data_to_mysql(exchange_urls)
